package de.rwth.dbis.ugnm.resource;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import de.rwth.dbis.ugnm.entity.Achievement;
import de.rwth.dbis.ugnm.service.AchievementService;

@Path("/achievements")
@Component
public class AchievementsResource {

	@Autowired
	AchievementService achievementService;
	
	@Context UriInfo uriInfo;
	
	@GET
	@Produces("application/json")
	public JSONObject getAchievements() {
		
		List<Achievement> achievements = achievementService.getAll();
		Iterator<Achievement> usit = achievements.iterator();
		
		Vector<String> vAchievements = new Vector<String>();	
		
		while(usit.hasNext()){
			Achievement m = usit.next();
			String mUri = uriInfo.getAbsolutePath().toASCIIString() + "/" + m.getId();
			vAchievements.add(mUri);
		}

		try {
			JSONObject j = new JSONObject();
			j.append("achievements",vAchievements);
			return j;
		} catch (JSONException e) {
			throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
		}
		
	}
	
	@POST
    @Consumes("application/json")
    public Response putAchievement(JSONObject o) throws JSONException {
        
		if(o == null || !(o.has("imgurl")) || !(o.has("name"))){
			throw new WebApplicationException(Status.BAD_REQUEST);
		}
		else{
        	Achievement newAchievement = new Achievement();
        	String murl = (String) o.get("imgurl");
        	String name = (String) o.get("name");
        	newAchievement.setImgUrl(murl);
        	newAchievement.setName(name);
        	
        	if(achievementService.getByName(name) == null) {
        		achievementService.save(newAchievement);
        		
        		Achievement mfdb = achievementService.getByName(name);
        		
        		URI location;
				try {
					location = new URI(uriInfo.getAbsolutePath().toASCIIString() + "/" + mfdb.getId());
					return Response.created(location).build();
				} catch (URISyntaxException e) {
					throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
				}
        	}
        	else{
        		throw new WebApplicationException(Status.CONFLICT);
        	}
        }
    }
	
}


